package com.bdqn.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatisUtil
 *
 * @author LILIBO
 * @since 2021-11-11
 */
public class MyBatisUtil {

    /**
     * SqlSessionFactory SqlSession工厂
     */
    private static SqlSessionFactory factory;

    static {
        // 读取MyBatis核心配置
        String resource = "mybatis-config.xml";
        try {
            // 获取mybatis-config.xml输入流
            InputStream is = Resources.getResourceAsStream(resource);
            // 使用SqlSessionFactoryBuilder读取配置文件并且构建SqlSessionFactory实例
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建并返回SqlSession实例
     *
     * @return
     */
    public static SqlSession createSqlSession() {
        return factory.openSession(true); // false 关闭自动提交事务
    }

    /**
     * 关闭SqlSession
     *
     * @param sqlSession
     */
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
